﻿using System.Collections.Generic;
using System.IO;
using System.Web.Mvc;
using EnetaMvc.ApplicationServices.Dto;

namespace EnetaMvc.Web.Extensions
{
    public class CommentRssResult : ActionResult
    {
        private List<CommentDto> _items;
        private string _title;
        private string _description;
        private string _urlPrefix;

        public CommentRssResult(IEnumerable<CommentDto> items, string title, string description, string urlPrefix)
        {
            _items = new List<CommentDto>(items);
            _title = title;
            _description = description;
            _urlPrefix = urlPrefix;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            context.HttpContext.Response.ContentType = "text/xml";

            using (var writer = new StreamWriter(context.HttpContext.Response.OutputStream))
            {
                writer.Write("<rss version=\"2.0\" ");
                writer.Write("xmlns:content=\"http://purl.org/rss/1.0/modules/content/\" ");
                writer.Write("xmlns:dc=\"http://purl.org/dc/elements/1.1/\" ");
                writer.Write("xmlns:slash=\"http://purl.org/rss/1.0/modules/slash/\" ");
                writer.Write("xmlns:wfw=\"http://wellformedweb.org/CommentAPI/\"");
                writer.WriteLine(">");

                writer.WriteLine("<channel>");

                writer.Write("<title>");
                writer.Write(_title);
                writer.WriteLine("</title>");
                writer.Write("<description>");
                writer.Write(_description);
                writer.WriteLine("</description>");

                _items.ForEach(x =>
                {
                    writer.WriteLine("<item>");
                    writer.Write("<title>");
                    writer.Write(x.Title);
                    writer.WriteLine("</title>");
                    writer.Write("<content:encoded>");
                    writer.Write(context.HttpContext.Server.HtmlEncode(x.Body));
                    writer.WriteLine("</content:encoded>");
                    writer.Write("<pubDate>");
                    writer.Write(x.Created.ToString("r"));
                    writer.WriteLine("</pubDate>");
                    writer.Write("<link>");
                    writer.Write(_urlPrefix + x.Id);
                    writer.WriteLine("</link>");
                    writer.Write("<dc:creator>");
                    writer.Write(x.AuthorUserName);
                    writer.WriteLine("</dc:creator>");
                    writer.WriteLine("</item>");
                });

                writer.WriteLine("</channel>");
                writer.Write("</rss>");
            }
        }
    }
}